package com.apes.scm.rbac.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.rop.securityManager.SampleSessionManager;
import com.apes.framework.rop.session.index.SessionIndexItem;
import com.apes.framework.rop.session.index.SessionIndexManager;
import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.repository.WorkPostRepository;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.repository.BranchRepository;
import com.apes.scm.rbac.model.LocalPermitItem;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.model.Role;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.LocalPermitItemRepository;
import com.apes.scm.rbac.repository.PostRepository;
import com.apes.scm.rbac.repository.RoleRepository;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能：岗位定义
 *
 * @author cxm
 * @create 2018-03-08 8:50
 * @desc 权限相关
 **/
@Service("postService")
public class PostService extends DomainService {
    @Autowired
    PostRepository postRepository;

    @Autowired
    LocalPermitItemRepository localPermitItemRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    BranchRepository branchRepository;

    @Autowired
    WorkPostRepository workPostRepository;

    @Autowired
    UserRepository userRepository;

    public Post save(SimpleRequest request) {
        Post post = request.getO(Post.class);
//        checkOrigin(post);
        // 重写 roles
        if (post.getRoles() != null) {
            Set<Role> roleSet = post.getRoles().stream().map(
                    (role) -> {
                        role = roleRepository.findOne(role.getId());
                        return role;
                    }
            ).collect(Collectors.toSet());
            post.setRoles(roleSet);
        }
        Post result = postRepository.saveAndFlush(post);
        removeSession(result);
        return result;
    }

    private void checkOrigin(Post post){
        List<Post> oldList = postRepository.findAllByOrigin(post.getOrigin());
        if (!oldList.isEmpty() && !post.getId().equals(oldList.get(0).getId())){
            throw new RuntimeException("外部id已经被"+oldList.get(0).getName()+"使用。");
        }
    }


    /*
     * 删除
     * */
    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Post post = postRepository.findOne(id);
        removeSession(post);
        postRepository.delete(post);
        return "删除成功！";
    }

    private void removeSession(Post post) {
        List<User> users = userRepository.findByPost(post.getId());
        if (users == null || users.isEmpty()) return;
        users.stream().forEach(user -> {
            List<SessionIndexItem> sessionIndexItems = (List<SessionIndexItem>) getBean(SessionIndexManager.class).get(user.getId());
            if (sessionIndexItems != null) {
                Iterator<SessionIndexItem> iterator = sessionIndexItems.iterator();
                while (iterator.hasNext()) {
                    SessionIndexItem item = iterator.next();
                    if (item.getPostId().equals(post.getId())) {
                        getBean(SampleSessionManager.class).removeSession(item.getSessionId());
                        iterator.remove();
                    }
                }
                if (sessionIndexItems.isEmpty()) getBean(SessionIndexManager.class).remove(user.getId());
                else getBean(SessionIndexManager.class).add(user.getId(), sessionIndexItems);
            }
        });
    }

    public Post findOne(String id) {
        return postRepository.findOne(id);
    }

    public Post findOne1(SimpleRequest request) {
        String id = request.get("id");
        return postRepository.findOne(id);
    }

    /**
     * 功能：下拉模糊查询使用
     *
     * @param request
     * @return
     */
    public Page<Post> find(SimpleRequest request) {
        return postRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 功能：查询行政部门和岗位对应 使用
     *
     * @param request
     * @return
     */
    public List<Post> findAllByBranchAndWorkPost(SimpleRequest request) {
        String branchId = request.get("branch");
        String workPostId = request.get("workPost");
        Branch branch = branchRepository.findOne(branchId);
        WorkPost workPost = workPostRepository.findOne(workPostId);
        return postRepository.findAllByBranchAndWorkPost(branch, workPost);
    }

    @Listener(topic = "event:aut.post.findLocalPermitItems")
    public List<String> findLocalPermitItems(SimpleRequest request) {
        Map date = request.getMap();
        return findLocalPermitItems((String) date.get("postId"), (String) date.get("purpose"), (String) date.get("type"));
    }

    public List<String> findLocalPermitItems(String postId, String purpose, String type) {
        List<LocalPermitItem> items = localPermitItemRepository.find(postId, purpose, type);
        return items.stream().map(item -> item.getOrgId()).collect(Collectors.toList());
    }


//    /**
//     *  生成 本地角色 和 同步到旧框架
//     * @param request
//     * @return
//     */
//    @Listener(topic = "event:cm.branchEntry.setPost")
//    public void setPost(SimpleRequest request) {
//        BranchEntry branchEntry = (BranchEntry) request.getData();
//        Post post = new Post();
//        post.setId("F"+branchEntry.getCompany().getId()+branchEntry.getId());
//        return findLocalPermitItems((String) date.get("postId"), (String) date.get("purpose"), (String) date.get("type"));
//    }


    /**
     * 返回行政岗位限价级别
     * @return
     */
    public String findPriLimitLevelCode(SimpleRequest request){
        String code ;
        try {
            Post post = postRepository.findOne(getSession(request).getPostId());
            code = post.getWorkPost().getPriLimitLevel().getCode();
        }catch (Exception e){
            throw new RuntimeException("该行政岗位未配置限价级别，请联系行政配置");
        }
        return code;
    }

    /**
     * 通过岗位id查询对应的公司查询权限
     * @param request postId
     * @return
     */
    public List<String> findLocalRoleByPost(SimpleRequest request){
        return postRepository.findLocalRoleByPost(request.getO(String.class)).stream().map(item -> (String) item.get("ID")).collect(Collectors.toList());
    }

}
